import os
import json
import time

from coin2.exchange.product_info import embed_source, SourceEnum


def filter_out_ico_symbol(symbols, pisf):
  with open(pisf) as fd:
    doc = json.load(fd)
    for info in doc["product_infos"]:
      native_symbol = info["native_symbol"]
      if any(key == native_symbol for key in symbols.keys()):
        del symbols[native_symbol]
  return symbols


def get_ico_symbol(mea, root_dir):
  symbols = {}
  if not os.path.exists(root_dir):
    print("ignored process ico symbol due to non-exist folder: %s" % root_dir)
    return True, symbols
  mea_json = f"%s/ico/%s.json" % (root_dir, mea)
  if not os.path.exists(mea_json):
    # print("ignored process ico symbol due to non-exist file: %s" % mea_json)
    return True, symbols
  with open(mea_json) as pi:
    doc = json.load(pi)
    for info in doc["product_infos"]:
      native_symbol = info["native_symbol"]
      if native_symbol in symbols:
        continue
      # info["source"] = "DUMMY"
      symbols[native_symbol] = info

  return len(symbols) == 0, symbols


def ioc_symbol_clear(mea, root_dir):
  symbols = {}
  if not os.path.exists(root_dir):
    print("ignored process ico symbol due to non-exist folder: %s" % root_dir)
    return True, symbols
  ico_mea_json = f"%s/ico/%s.json" % (root_dir, mea)
  if not os.path.exists(ico_mea_json):
    # print("ignored process ico symbol due to non-exist file: %s" % mea_json)
    return True, symbols
  with open(ico_mea_json) as pi:
    ico_pis = json.load(pi)

  pisf = f"data/coin2/product_info/%s.json" % mea
  if not os.path.exists(pisf):
    # exception
    return
  with open(pisf) as pi:
    data_pis = json.load(pi)

  listed_pi_set = set()
  for pi in data_pis["product_infos"]:
    listed_pi_set.add(pi["native_symbol"])

  ico_dump_pis = []
  for pi in ico_pis["product_infos"]:
    if pi["native_symbol"] not in listed_pi_set:
      ico_dump_pis.append(pi)

  ico_pis["product_infos"] = ico_dump_pis
  with open(ico_mea_json, "w+") as fd:
    json.dump(ico_pis, fd, indent=2)


def add_ico_symbol(mea, coin_product_info_dir):
  ignore, symbols = get_ico_symbol(mea, coin_product_info_dir)
  if ignore:
    return
  pisf = f"data/coin2/product_info/%s.json" % mea
  if not os.path.exists(pisf):
    # exception
    return
  symbols = filter_out_ico_symbol(symbols, pisf)

  mea = None
  fetched_time = None
  product_infos = []
  with open(pisf) as fd:
    doc = json.load(fd)
    mea = doc['mea']
    fetched_time = doc['fetched_time']
    product_infos.extend(doc['product_infos'])
  for info in symbols.values():
    info["fetched_time"] = embed_source(fetched_time, SourceEnum.DUMMY)
  product_infos.extend(symbols.values())
  doc = {
      "mea": mea,
      "fetched_time": fetched_time,
      "product_infos": product_infos,
  }
  with open(pisf, 'w') as fd:
    json.dump(doc, fd, indent=2)
